package xyz.scootaloo.kami.cloud.handler

import io.vertx.ext.web.Router
import io.vertx.kotlin.coroutines.await
import xyz.scootaloo.kami.cloud.lang.Constant
import xyz.scootaloo.kami.cloud.lang.Constant.OK
import xyz.scootaloo.kami.cloud.lang.EventLoop
import xyz.scootaloo.kami.cloud.lang.getLogger
import xyz.scootaloo.kami.cloud.model.po.AccountForm
import xyz.scootaloo.kami.cloud.service.AccountService
import xyz.scootaloo.kami.cloud.service.TokenService

/**
 * @author flutterdash@qq.com
 * @since 2022/4/12 22:44
 */
@EventLoop(Constant.CTX_SERVER)
object AccountHandler : RequestHandlerRegister {

    private val accountService = AccountService()
    private val tokenService = TokenService()

    override val log by lazy { getLogger("account-router") }
    override val mountPoint = "/account"

    override fun register(router: Router) = router.run {
        get("/") { ctx ->
            val token = tokenService.generateToken(ctx.remoteIpAddress()).await()
            ctx.reply(token)
        }

        post("/register") { ctx ->
            val form = ctx.readBodyAsJson<AccountForm>()
            val rsl = accountService.register(ctx.remoteIpAddress(), form).await()
            ctx.reply(rsl.result, rsl.code)
        }

        post("/login") { ctx ->
            val form = ctx.readBodyAsJson<AccountForm>()
            val rsl = accountService.login(ctx.remoteIpAddress(), form).await()
            ctx.reply(rsl.result, rsl.code)
        }

        post("/logout") { ctx ->
            ctx.reply(OK)
        }
    }
}